using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class ShopKeeperDisplay : MonoBehaviour
{
    [Header("商店槽预制体")]
    [SerializeField] private ShopSlotUI _shopSlotPrefab;
    [Header("购物车物品预制体")]
    [SerializeField] private ShoppingCartItemUI _shoppingCartItemPrefab;
    [Header("购买标签按钮")]
    [SerializeField] private Button _buyTabButton;
    [Header("出售标签按钮")]
    [SerializeField] private Button _sellTabButton;

    [Space]
    [Header("购物车")]
    [Header("购物车总价文本")]
    [SerializeField] private TextMeshProUGUI _basketTotalText;
    [Header("玩家金币数文本")]
    [SerializeField] private TextMeshProUGUI _playerGoldText;
    [Header("商店金币数文本")]
    [SerializeField] private TextMeshProUGUI _shopGoldText;
    [Header("购买按钮")]
    [SerializeField] private Button _buyButton;
    [Header("购买按钮文本")]
    [SerializeField] private TextMeshProUGUI _buyButtonText;

    [Space]
    [Header("物品预览区域")]
    [Header("物品预览图像")]
    [SerializeField] private Image _itemPreviewSprite;
    [Header("物品名称文本")]
    [SerializeField] private TextMeshProUGUI _itemPreviewName;
    [Header("物品描述文本")]
    [SerializeField] private TextMeshProUGUI _itemPreviewDescription;
    [Header("物品列表内容面板")]
    [SerializeField] private GameObject _itemListContentPanel;
    [Header("购物车物品列表内容面板")]
    [SerializeField] private GameObject _shoppingCartContentPanel;

    private bool _isSelling;// 是否为出售模式
    private int _basketTotal;// 购物车总价格
    private ShopSystem _shopSystem;// 商店系统组件
    private PlayerInventoryHolder _playerInventoryHolder;
    private Dictionary<InventoryItemData, int> _shoppingCart = new Dictionary<InventoryItemData, int>(); // 购物车字典
    private Dictionary<InventoryItemData, ShoppingCartItemUI> _shoppingCartUI = new Dictionary<InventoryItemData, ShoppingCartItemUI>();// 显示购物车物品信息的字典
    public void DisplayShopWindow(ShopSystem shopSystem, PlayerInventoryHolder playerInventoryHolder)
    {
        _shopSystem = shopSystem;
        _playerInventoryHolder = playerInventoryHolder;
        RefreshDisplay();
    }
    private void RefreshDisplay()
    {
        if (_buyButton != null)
        {
            // 设置购买按钮的文字和点击事件
            _buyButtonText.text = _isSelling ? "Sell" : "Buy";
            _buyButton.onClick.RemoveAllListeners();
            if (_isSelling) _buyButton.onClick.AddListener(SellItems);
            else _buyButton.onClick.AddListener(BuyItems);
        }

        // 清除物品槽，并隐藏购物篮总价和购买按钮
        ClearSlots();

        _basketTotalText.enabled = false;
        _buyButton.gameObject.SetActive(false);
        _basketTotal = 0;

        // 显示玩家和商店的金币数量
        _playerGoldText.text = $"PLayer Gold:{_playerInventoryHolder.PrimaryInventorySystem.Gold}";
        _shopGoldText.text = $"Shop Gold:{_shopSystem.AvailableGold}";

        // 清空物品预览
        ClearItemPreview();
        if (_isSelling) DisplayPlayerInventory(); // 如果是卖家，显示玩家的库存
        else DisplayShopInventory();// 否则显示商店的库存  
    }

    //显示玩家的库存
    private void DisplayPlayerInventory()
    {
        foreach (var item in _playerInventoryHolder.PrimaryInventorySystem.GetAllItemsHeld())
        {
            var tempSlot = new ShopSlot();
            tempSlot.AssignItem(item.Key, item.Value);// 分配物品
            var shopSlot = Instantiate(_shopSlotPrefab, _itemListContentPanel.transform);
            shopSlot.Init(tempSlot, _shopSystem.SellMarkUp);// 初始化槽位
        }
    }

    private void ClearSlots()
    {
        _shoppingCart = new Dictionary<InventoryItemData, int>();
        _shoppingCartUI = new Dictionary<InventoryItemData, ShoppingCartItemUI>();
        // 清空物品列表内容面板和购物车物品列表内容面板中的所有子物体
        foreach (var item in _itemListContentPanel.transform.Cast<Transform>())
        {
            Destroy(item.gameObject);
        }
        foreach (var item in _shoppingCartContentPanel.transform.Cast<Transform>())
        {
            Destroy(item.gameObject);
        }
    }

    private void DisplayShopInventory()
    {
        // 遍历商店物品列表，显示每个物品槽
        foreach (var item in _shopSystem.ShopInventory)
        {
            if (item.ItemData == null) continue;
            var shopSlot = Instantiate(_shopSlotPrefab, _itemListContentPanel.transform);
            shopSlot.Init(item, _shopSystem.BuyMarkUp);
        }
    }

    // 从购物车中移除该物品槽对应的物品
    public void RemoveItemFromCart(ShopSlotUI shopSlotUI)
    {
        var data = shopSlotUI.AssignedItemSlot.ItemData;
        var price = GetModifiedPrice(data, 1, shopSlotUI.MarkUp);// 获取物品的价格
        if (_shoppingCart.ContainsKey(data))// 如果购物车中存在该物品
        {
            _shoppingCart[data]--;// 将物品数量减1
            // 更新该物品UI的显示
            var newString = $"{data.DisplayName}({price}G) x{_shoppingCart[data]}";
            _shoppingCartUI[data].SetItemText(newString);
            // 如果移除该物品后，该物品数量为0
            if (_shoppingCart[data] <= 0)
            {
                // 从购物车和UI字典中移除该物品
                _shoppingCart.Remove(data);
                var tempobj = _shoppingCartUI[data].gameObject;// 获取该物品UI对象
                _shoppingCartUI.Remove(data);
                Destroy(tempobj);// 销毁该物品UI对象
            }
        }

        _basketTotal -= price; // 减去该物品的价格
        _basketTotalText.text = $"Total:{_basketTotal}G";// 更新购物车总价UI的文本显示
        // 如果购物车总价小于等于0且购物车总价UI处于激活状态
        if (_basketTotal <= 0 && _basketTotalText.IsActive())
        {
            _basketTotalText.enabled = false;// 关闭购物车总价UI的显示
            _buyButton.gameObject.SetActive(false);// 隐藏购买按钮
            ClearItemPreview();// 清空物品预览
            return;
        }
        // 检查购物车总价和玩家拥有的金币数是否匹配
        CheckCartVsAvailableGold();
    }

    // 清空物品预览
    private void ClearItemPreview()
    {
        _itemPreviewSprite.sprite = null;
        _itemPreviewSprite.color = Color.clear;
        _itemPreviewName.text = "";
        _itemPreviewDescription.text = "";
    }

    // 将该物品槽对应的物品添加到购物车中
    public void AddItemToCart(ShopSlotUI shopSlotUI)
    {
        // 获取物品数据
        var data = shopSlotUI.AssignedItemSlot.ItemData;

        // 更新物品预览
        UpdateItemPreview(shopSlotUI);

        var price = GetModifiedPrice(data, 1, shopSlotUI.MarkUp);// 获取修改后的价格
        if (_shoppingCart.ContainsKey(data))
        {
            _shoppingCart[data]++;
            var newString = $"{data.DisplayName} ({price}G)x{_shoppingCart[data]}";// 如果购物车中已经有该物品，增加其数量
            _shoppingCartUI[data].SetItemText(newString);// 更新显示购物车物品信息的文本组件
        }
        else
        {
            _shoppingCart.Add(data, 1);// 否则，在购物车中添加该物品
            var shoppingCartTextObj = Instantiate(_shoppingCartItemPrefab, _shoppingCartContentPanel.transform);// 创建一个新的显示购物车物品信息的文本组件
            var newString = $"{data.DisplayName} ({price}G)x1";
            shoppingCartTextObj.SetItemText(newString);
            _shoppingCartUI.Add(data, shoppingCartTextObj); // 添加到显示购物车物品信息的字典中
        }

        _basketTotal += price;
        _basketTotalText.text = $"Total:{_basketTotal}G";// 更新购物车总价格的文本显示

        if (_basketTotal > 0 && !_basketTotalText.IsActive())
        {
            _basketTotalText.enabled = true;// 如果购物车总价大于 0 且文本组件是激活状态，启用文本组件
            _buyButton.gameObject.SetActive(true);// 激活“购买”按钮
        }

        CheckCartVsAvailableGold();
    }

    // 更新物品预览
    private void UpdateItemPreview(ShopSlotUI shopSlotUI)
    {
        var data = shopSlotUI.AssignedItemSlot.ItemData;
        _itemPreviewSprite.sprite = data.Icon;
        _itemPreviewSprite.color = Color.white;
        _itemPreviewName.text = data.DisplayName;
        _itemPreviewDescription.text = data.Description;
    }

    /// <summary>
    /// 获取修改后的价格
    /// </summary>
    /// <param name="data">物品数据</param>
    /// <param name="amount">物品数量</param>
    /// <param name="markUp">加价比例</param>
    /// <returns>修改后的价格</returns>
    public static int GetModifiedPrice(InventoryItemData data, int amount, float markUp)
    {
        // 计算基础价格，即物品单价乘以数量
        var baseValue = data.GoldValue * amount;
        // 计算调整后的价格，即基础价格加上涨价比例所得到的价格, 结果向下取整
        return Mathf.FloorToInt(baseValue + baseValue * markUp);
    }

    //检查购物车与可用金币数之间的比较
    private void CheckCartVsAvailableGold()
    {
        Debug.Log("检查购物车与可用金币数之间的比较");

        // 如果是出售模式，获取商店可用金币数，否则获取玩家背包的金币数
        var goldToCheck = _isSelling ? _shopSystem.AvailableGold : _playerInventoryHolder.PrimaryInventorySystem.Gold;

        // 如果购物车总价大于可用金币数，将文本颜色设置为红色，否则为白色
        _basketTotalText.color = _basketTotal > goldToCheck ? Color.red : Color.white;
        // 如果是出售模式或者玩家背包还有足够的空间，则直接返回
        if (_isSelling || _playerInventoryHolder.PrimaryInventorySystem.CheckInventoryRemaining(_shoppingCart)) return;
        //库存不足
        _basketTotalText.text = "Insufficient inventory";
        _basketTotalText.color = Color.red;
    }

    // 出售点击事件
    private void SellItems()
    {
        // 如果商店可用金币少于购物车中物品的总价值，则无法出售
        if (_shopSystem.AvailableGold < _basketTotal)
            return;

        // 遍历购物车中的物品
        foreach (var kvp in _shoppingCart)
        {
            // 获取物品的调整价格
            var price = GetModifiedPrice(kvp.Key, kvp.Value, _shopSystem.SellMarkUp);

            // 在商店中出售物品，并减少商店金额
            _shopSystem.SellItem(kvp.Key, kvp.Value, price);

            // 玩家增加金币
            _playerInventoryHolder.PrimaryInventorySystem.GainGold(price);

            // 从玩家库存系统中移除出售的物品
            _playerInventoryHolder.PrimaryInventorySystem.RemoveItemsFromInventory(kvp.Key, kvp.Value);
        }

        // 刷新显示
        RefreshDisplay();
    }


    //购买点击事件
    private void BuyItems()
    {
        // 检查玩家是否有足够的金币购买所有物品
        if (_playerInventoryHolder.PrimaryInventorySystem.Gold < _basketTotal)
        {
            Debug.Log("玩家金币不足");
            return;
        }
        // 检查玩家背包是否有足够的空间存放购物车中的物品
        if (!_playerInventoryHolder.PrimaryInventorySystem.CheckInventoryRemaining(_shoppingCart))
        {
            Debug.Log("玩家背包位置不足");
            return;
        }
        // 逐个购买购物车中的物品并添加到玩家背包中
        foreach (var kvp in _shoppingCart)
        {
            _shopSystem.PurchaseItem(kvp.Key, kvp.Value);
            for (int i = 0; i < kvp.Value; i++)
            {
                _playerInventoryHolder.PrimaryInventorySystem.AddToInventory(kvp.Key, 1);
            }

        }
        // 商店获得金币，玩家失去金币
        _shopSystem.GainGold(_basketTotal);
        _playerInventoryHolder.PrimaryInventorySystem.SpendGold(_basketTotal);

        // 刷新商店界面显示
        RefreshDisplay();
    }

    public void OnBuyTabPressed()
    {
        _isSelling = false;
        RefreshDisplay();
    }
    public void OnSellTabPressed()
    {
        _isSelling = true;
        RefreshDisplay();
    }
}
